package org.dromara.wmscloud.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import lombok.RequiredArgsConstructor;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.constraints.*;
import cn.dev33.satoken.annotation.SaCheckPermission;
import org.dromara.wmscloud.bean.MatLabelPdfData;
import org.dromara.wmscloud.bean.typeEnum.InOrderTypeEnum;
import org.dromara.wmscloud.utils.PDFService;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import org.dromara.common.idempotent.annotation.RepeatSubmit;
import org.dromara.common.log.annotation.Log;
import org.dromara.common.web.core.BaseController;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.validate.AddGroup;
import org.dromara.common.core.validate.EditGroup;
import org.dromara.common.log.enums.BusinessType;
import org.dromara.common.excel.utils.ExcelUtil;
import org.dromara.wmscloud.domain.vo.StockMatLabelVo;
import org.dromara.wmscloud.domain.bo.StockMatLabelBo;
import org.dromara.wmscloud.service.IStockMatLabelService;
import org.dromara.common.mybatis.core.page.TableDataInfo;

/**
 * 物料标签
 *
 * @author hou
 * @date 2025-04-12
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/wmsCloud/matLabel")
public class StockMatLabelController extends BaseController {

    private final IStockMatLabelService stockMatLabelService;
    private final PDFService pdfService;
    /**
     * 查询物料标签列表
     */
    @SaCheckPermission("stock:matLabel:list")
    @GetMapping("/list")
    public TableDataInfo<StockMatLabelVo> list(StockMatLabelBo bo, PageQuery pageQuery) {
        return stockMatLabelService.queryPageList(bo, pageQuery);
    }

    /**
     * 查询物料标签列表
     */
    @SaCheckPermission("stock:matLabel:list")
    @GetMapping("/listDialog")
    public TableDataInfo<StockMatLabelVo> listDialog(StockMatLabelBo bo, PageQuery pageQuery) {
        return stockMatLabelService.queryDialogList(bo, pageQuery);
    }

    /**
     * 导出物料标签列表
     */
    @SaCheckPermission("stock:matLabel:export")
    @Log(title = "物料标签", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(StockMatLabelBo bo, HttpServletResponse response) {
        List<StockMatLabelVo> list = stockMatLabelService.queryList(bo);
        ExcelUtil.exportExcel(list, "物料标签", StockMatLabelVo.class, response);
    }

    /**
     * 获取物料标签详细信息
     *
     * @param labelId 主键
     */
    @SaCheckPermission("stock:matLabel:query")
    @GetMapping("/{labelId}")
    public R<StockMatLabelVo> getInfo(@NotNull(message = "主键不能为空")
                                     @PathVariable Long labelId) {
        return R.ok(stockMatLabelService.queryById(labelId));
    }

    /**
     * 新增物料标签
     */
    @SaCheckPermission("stock:matLabel:add")
    @Log(title = "物料标签", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody StockMatLabelBo bo) {
        return toAjax(stockMatLabelService.insertByBo(bo));
    }

    /**
     * 修改物料标签
     */
    @SaCheckPermission("stock:matLabel:edit")
    @Log(title = "物料标签", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody StockMatLabelBo bo) {
        return toAjax(stockMatLabelService.updateByBo(bo));
    }

    /**
     * 删除物料标签
     *
     * @param labelIds 主键串
     */
    @SaCheckPermission("stock:matLabel:remove")
    @Log(title = "物料标签", businessType = BusinessType.DELETE)
    @DeleteMapping("/{labelIds}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable Long[] labelIds) {
        return toAjax(stockMatLabelService.deleteWithValidByIds(List.of(labelIds), true));
    }

    /**
     * 打印物料标签
     *
     *  @param labelId 主键串
     */
    @SaCheckPermission("stock:matLabel:print")
    @Log(title = "物料标签", businessType = BusinessType.OTHER)
    @GetMapping("printMatLabel/{labelId}")
    public void printMatLabel(HttpServletResponse response, @PathVariable Long labelId) throws Exception{
        OutputStream out = response.getOutputStream();
        response.setContentType("application/pdf");
        StockMatLabelVo stockMatLabel = stockMatLabelService.queryById(labelId);
        if(stockMatLabel != null){

            MatLabelPdfData matLabelPdfData = new MatLabelPdfData();
            matLabelPdfData.setSupplierName(stockMatLabel.getSupplierName());
            matLabelPdfData.setMatCode(stockMatLabel.getMatCode());
            matLabelPdfData.setMatName(stockMatLabel.getMatName());
            matLabelPdfData.setFigNum(stockMatLabel.getFigNum());
            matLabelPdfData.setQuantity(stockMatLabel.getQuantity());
            matLabelPdfData.setUnitCode(stockMatLabel.getUnitCode());
            matLabelPdfData.setOrderNo(stockMatLabel.getOrderNo());
            matLabelPdfData.setOrderType(InOrderTypeEnum.getLabel(stockMatLabel.getOrderType()));
            matLabelPdfData.setBatch(stockMatLabel.getBatch());
            matLabelPdfData.setProdTime(stockMatLabel.getProdTime());
            InputStream in = new FileInputStream(new File(pdfService.printMatLabel(matLabelPdfData,1)));
            int len = 0;
            byte[] buffer = new byte[1024];
            while ((len = in.read(buffer)) > 0) {
                out.write(buffer, 0, len);
            }

            in.close();
        }
    }

    /**
     * 批量打印物料标签
     *
     *  @param labelIds 主键串
     */
    @SaCheckPermission("stock:matLabel:print")
    @Log(title = "物料标签", businessType = BusinessType.OTHER)
    @GetMapping("printMatLabelBatch/{labelIds}")
    public void printLabelBatch(HttpServletResponse response, @PathVariable Long[] labelIds) throws Exception {
        // 设置响应内容类型
        response.setContentType("application/pdf");

        // 查询物料标签数据
        List<StockMatLabelVo> stockMatLabelVos = stockMatLabelService.queryByIds(labelIds);
        List<MatLabelPdfData> pdfDataList = new ArrayList<>();
        for (StockMatLabelVo labelId : stockMatLabelVos) {
            MatLabelPdfData matLabelPdfData = new MatLabelPdfData();
            matLabelPdfData.setSupplierName(labelId.getSupplierName());
            matLabelPdfData.setMatCode(labelId.getMatCode());
            matLabelPdfData.setMatName(labelId.getMatName());
            matLabelPdfData.setFigNum(labelId.getFigNum());
            matLabelPdfData.setQuantity(labelId.getQuantity());
            matLabelPdfData.setUnitCode(labelId.getUnitCode());
            matLabelPdfData.setOrderNo(labelId.getOrderNo());
            matLabelPdfData.setOrderType(InOrderTypeEnum.getLabel(labelId.getOrderType()));
            matLabelPdfData.setBatch(labelId.getBatch());
            matLabelPdfData.setProdTime(labelId.getProdTime());
            pdfDataList.add(matLabelPdfData);
        }
        // 使用 try-with-resources 确保资源关闭
        try (OutputStream out = response.getOutputStream();
             InputStream in = new FileInputStream(new File(pdfService.printLabelBatch(pdfDataList)))) {
            byte[] buffer = new byte[1024];
            int len;
            while ((len = in.read(buffer)) > 0) {
                out.write(buffer, 0, len);
            }
        }
    }
}
